<template>
  <view>

    <!-- 第三方登录 -->
    <view class="oauth">
      <view class="text">— 授权获取用户信息 —</view>
      <view class="list">
        <view class="oauth-image" v-for="provider in providerList" :key="provider.value">
          <button v-if="!isDevtools" @click="newWxLogin">确认授权</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import md5 from "@/common/SDK/md5.min.js";
import {common} from "@/common/httpApi";
import {CommonApi} from "@/api/user";

export default {
  data() {
    return {
      code: '',
      phoneNumber: '',
      passwd: '',
      isShowOauth: false,
      providerList: [],
      showProvider: {
        weixin: true,
        qq: false,
        sinaweibo: false,
        xiaomi: false
      }
    }
  },
  onShow() {

  },
  onLoad() {
    //APP显示第三方登录
    // #ifdef APP-PLUS
    this.isShowOauth = true;
    // #endif
    this.getProvider();
    this.oauth('weixin');
  },
  onReady() {
    this.initPosition();
    this.initProvider();
    // #ifdef MP-WEIXIN
    this.isDevtools = uni.getSystemInfoSync().platform === 'devtools';
    // #endif
  },
  methods: {
    getPhoneNumber(e) {
      //              console.log(JSON.stringify(e.encryptedData));
      //              console.log(JSON.stringify(e.iv));
    },
    initProvider() {
      const filters = ['weixin'];
      uni.getProvider({
        service: 'oauth',
        success: (res) => {
          if (res.provider && res.provider.length) {
            for (let i = 0; i < res.provider.length; i++) {
              if (~filters.indexOf(res.provider[i])) {
                this.providerList.push({
                  value: res.provider[i],
                  image: 'http://120.55.49.138/ShopMall/static/img/' + res.provider[i] + '.png'
                });
              }
            }
            this.hasProvider = true;
          }
        },
        fail: (err) => {
          console.error('获取服务供应商失败：' + JSON.stringify(err));
        }
      });
    },
    oauth(value) {
      uni.login({
        provider: value,
        success: (res) => {
          let data = {}
          // #ifdef MP-WEIXIN
          data = {code: res.code}
          this.code = res.code
          // #endif
          // #ifdef APP-PLUS
          data = {
            type: 1,//0 qq 1 weixin(app) 2 weibo 3weixin(h5) 4微信小程序
            access_token: res.authResult.access_token,
            openid: res.authResult.openid
          }
          // #endif

          res.code && this.$Request.post(this.$api.sso.getOpenid + '?code=' + this.code).then(res => {

            if (res.code == 200) {
              let openid = res.data.openid;
              let session_key = res.data.session_key;
              uni.setStorageSync("openid", openid);
              uni.setStorageSync("session_key", session_key);
              if (res.data.has_member == '0') {
                uni.showToast({title: '该用户没有注册，请先注册。', icon: "none"});
                setTimeout(function () {
                  uni.navigateTo({
                    url: "./register"
                  });
                }, 1000)
              }
            }
          })
        },
        fail: (err) => {
          console.error('授权登录失败：' + JSON.stringify(err));
          uni.showToast({
            icon: 'none',
            title: '授权登录失败：' + JSON.stringify(err)
          });

        }
      });
    },
    newWxLogin() {
      uni.getUserProfile({
        desc: '登录',
        success: (res) => {
          console.log(res)
          // uni.navigateTo({
          // 	url:'./loginPhone'
          // })
          let detail = res.userInfo
          var openid = uni.getStorageSync("openid");
          var session_key = uni.getStorageSync("session_key");
          detail.openid = openid;
          detail.session_key = session_key;
          detail.openid = openid;

          var data = {
            "city": detail.city,
            "country": detail.country,
            "headimgurl": detail.avatarUrl,
            "id": 0,
            "loginTime": "",
            "nickname": detail.nickName,
            "openid": detail.openid,
            "province": detail.province,
            "sex": detail.gender,
            "unionid": ''
          };
          uni.setStorageSync("username", detail.nickName);
          uni.setStorageSync("face", detail.avatarUrl);


          this.$Request.post(this.$api.sso.loginByWX, data).then(res => {

            if (res.code == 200) {
              var cookies = res.data.token;
              var hearder = res.data.tokenHead;
              uni.setStorageSync("sessionid", cookies);
              uni.setStorageSync("hearder", hearder);

              //绑定手机
              let phone = uni.getStorageSync("phoneNumber");
              if (phone) {
                CommonApi.bindPhone({phone})
              }
              uni.showToast({title: '登录成功', icon: "success"});
              setTimeout(function () {
                uni.switchTab({
                  url: '/pages/tabBar/user/user',
                  success: res => {

                  }, fail: (err) => {
                    console.log(err)
                  }, complete: () => {

                  }
                })
              }, 1000)
            }
          })


        },
        fail: (err) => {
          console.log(err);
        }
      })
    },
    getUserInfo({
                  detail
                }) {
      console.log('detail:', detail);
      if (detail.userInfo) {

        //setTimeout(()=>{
        //uni.showToast({title: '验证码已发送',icon:"none"});
        //示例默认1234，生产中请删除这一句。
        //this.code=1234;
        var openid = uni.getStorageSync("openid");
        var session_key = uni.getStorageSync("session_key");
        detail.openid = openid;
        detail.session_key = session_key;
        detail.userInfo.openid = openid;

        console.log(detail.userInfo);
        var data = {
          "city": detail.userInfo.city,
          "country": detail.userInfo.country,
          "headimgurl": detail.userInfo.avatarUrl,
          "id": 0,
          "loginTime": "",
          "nickname": detail.userInfo.nickName,
          "openid": detail.userInfo.openid,
          "province": detail.userInfo.province,
          "sex": detail.userInfo.gender,
          "unionid": ''
        };
        uni.setStorageSync("username", detail.userInfo.nickName);
        uni.setStorageSync("face", detail.userInfo.avatarUrl);


        this.$Request.post(this.$api.sso.loginByWX, data).then(res => {

          if (res.code == 200) {
            var cookies = res.data.token;
            var hearder = res.data.tokenHead;
            uni.setStorageSync("sessionid", cookies);
            uni.setStorageSync("hearder", hearder);

            //uni.setStorageSync("rememberMe",cookies[1]);
            uni.showToast({title: '登录成功', icon: "success"});
            setTimeout(function () {
              uni.navigateBack();
            }, 1000)
          }
        })
        //this.setTimer();
        //},1000)
      } else {
        uni.showToast({
          icon: 'none',
          title: '登陆失败'
        });
      }
    },
    initPosition() {
      /**
       * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
       * 反向使用 top 进行定位，可以避免此问题。
       */
      this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
    },
    oauthLogin(provider) {
      uni.showLoading();
      //第三方登录
      uni.login({
        provider: provider,
        success: (loginRes) => {
          console.log("success: " + JSON.stringify(loginRes));
          //案例直接获取用户信息，一般不是在APP端直接获取用户信息，比如微信，获取一个code，传递给后端，后端再去请求微信服务器获取用户信息
          uni.getUserInfo({
            provider: provider,
            success: (infoRes) => {
              console.log('用户信息：' + JSON.stringify(infoRes.userInfo));
              setTimeout(() => {
                //uni.showToast({title: '验证码已发送',icon:"none"});
                //示例默认1234，生产中请删除这一句。
                //this.code=1234;
                this.$Request.post(this.$api.sso.signinWXUser + '?code=' + this.code).then(res => {

                  if (res.code == 200) {
                    var cookies = res.data.token;
                    var hearder = res.data.tokenHead;
                    uni.setStorageSync("sessionid", cookies);
                    uni.setStorageSync("hearder", hearder);
                    uni.setStorageSync("username", infoRes.userInfo.nickName);
                    uni.setStorageSync("face", infoRes.userInfo.avatarUrl);
                    //uni.setStorageSync("rememberMe",cookies[1]);
                    //uni.showToast({title: '登录成功',icon:"success"});
                    uni.setStorage({
                      key: 'UserInfo',
                      data: {
                        username: infoRes.userInfo.nickName,
                        face: infoRes.userInfo.avatarUrl,
                        signature: '个性签名',
                        integral: 0,
                        balance: 0,
                        envelope: 0
                      },
                      success: function () {
                        uni.hideLoading()
                        uni.showToast({title: '微信登录成功', icon: "success"});
                        setTimeout(function () {
                          uni.navigateBack();
                        }, 300)
                      }
                    });
                  }
                })
                //this.setTimer();
              }, 1000)


            }
          });
        },
        fail: (e) => {
          console.log("fail: " + JSON.stringify(e));
        }
      });
    },
    getProvider() {
      //获取第三方登录服务
      uni.getProvider({
        service: 'oauth',
        success: (res) => {
          let len = res.provider.length;
          for (let i = 0; i < len; i++) {
            //有服务才显示按钮图标
            this.showProvider[res.provider[i]] = true;
          }
          if (res.provider.length == 0) {
            this.isShowOauth = false;
          } else {
            this.isShowOauth = true;
          }
        }
      });
    },
    toPage(page) {
      uni.hideKeyboard()
      uni.navigateTo({
        url: page
      });
    },
    doLogin() {
      uni.hideKeyboard();
      //验证手机号码
      if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phoneNumber))) {
        uni.showToast({title: '请填写正确手机号码', icon: "none"});
        return false;
      }
      uni.showLoading({
        title: '提交中...'
      })
      //模板示例比对本地储存的用户信息，实际使用中请替换为上传服务器比对。
      setTimeout(() => {
        let md5PW = md5(this.passwd);

        var data = {
          'username': 'user' + this.phoneNumber,
          'password': md5(this.passwd),
          'phone': this.phoneNumber,
          'code': this.code
        };

        this.$Request.post(this.$api.sso.login, data).then(res => {

          if (res.code == 200) {
            var cookies = res.data.token;
            var hearder = res.data.tokenHead;
            uni.setStorageSync("sessionid", cookies);
            uni.setStorageSync("hearder", hearder);

            uni.setStorage({
              key: 'UserInfo',
              data: {
                username: infoRes.userInfo.nickName,
                face: infoRes.userInfo.avatarUrl,
                signature: '个性签名',
                integral: 0,
                balance: 0,
                envelope: 0
              },
              success: function () {
                uni.hideLoading()
                uni.showToast({title: '登录成功', icon: "success"});
                setTimeout(function () {
                  uni.navigateBack();
                }, 300)
              }
            });
          } else {
            uni.showToast({title: '账号或密码不正确', icon: "none"});
            return;
          }
        })

      }, 1000)
    }
  }
}
</script>

<style lang="scss">
@import "../../static/css/login.scss";

.form {
  .res {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100upx;
    color: rgba($color: #ffffff, $alpha: 0.8);
  }
}

.oauth {
  @media all and (max-height: 150vw) {
    display: none;
  }
  position: absolute;
  bottom: 50upx;
  width: 100%;

  .text {
    width: 100%;
    height: 60upx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba($color: #ffffff, $alpha: 0.8);
    font-size: 28upx;
  }

  .list {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20upx 0;

    .icon {
      font-size: 80upx;
      margin: 0 30upx;
    }
  }
}

.oauth-row {
  display: flex;
  flex-direction: row;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}

.oauth-image {
  position: relative;
  width: 220upx;
  height: 60upx;
  line-height: 60upx;
}

.oauth-image button {
  width: 220upx;
  height: 60upx;
  line-height: 60upx;
  text-align: center;
  background: #fff;
  color: #333;
  font-size: 28upx;
}
</style>
